// @flow
import React, { Component } from 'react'
import styles from './TaskListActions.css'
import { Button, Popconfirm, message, notification, Switch, Tooltip } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  refreshTaskList: Function,
  data: Object,
  history: Object
}

type State = {
  modelPresent: boolean,
  taskData: Object,
  disabled: boolean,
  disableLable: string
}

class TaskListActions extends Component {
  props: Props
  state: State
  deleteTask: Function
  runTask: Function
  closeModel: Function
  getTaskData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      modelPresent: true,
      taskData: {},
      disabled: false,
      disableLable: ''
    }
    this.deleteTask = this.deleteTask.bind(this)
    this.runTask = this.runTask.bind(this)
    this.closeModel = this.closeModel.bind(this)
    this.getTaskData = this.getTaskData.bind(this)
  }
  componentWillMount () {
    const { data } = this.props
    if (data.model == null) {
      this.setState({
        modelPresent: false
      })
    } else {
      const tmpFlag = data.model.useFulTemplate
      if (!tmpFlag) {
        this.setState({
          disabled: true,
          disableLable: '由于关联模型已经失效,该任务不可用'
        })
      }
    }
  }
  getTaskData () {
    const { history, data } = this.props
    universalFetch(`${__SERVICE_API__}analysis/tasks/${data.id}`)
      .then((res) => res.json())
      .then((json) => {
        history.push({
          pathname: '/analysis/task-edit',
          state: {
            data: json.result
          } })
        this.setState({
          taskData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  closeModel (checked) {
    const { data } = this.props
    const tmpFlag = data.model.useFulTemplate
    if (!tmpFlag) {
      notification.error({
        message: '提醒',
        description: '由于关联模型已经失效,该任务不可用',
        duration: 7
      })
    } else {
      universalFetch(`${__SERVICE_API__}analysis/models/${data.modelIdCopy}?useful=${checked}`,
        {
          method: 'PUT'
        })
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          message.success('操作成功')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('操作失败')
        })
    }
  }
  deleteTask () {
    const { data } = this.props
    universalFetch(`${__SERVICE_API__}analysis/tasks/${data.id}`, {
      method: 'DELETE'
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        notification.error({
          message: '任务启动提醒',
          description: json.message,
          duration: 7
        })
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.props.refreshTaskList()
      message.success('删除成功')
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('删除失败')
    })
  }
  runTask () {
    const { data } = this.props
    console.log(data)
    const tmpFlag = data.model.useFul
    if (!tmpFlag) {
      notification.error({
        message: '提醒',
        description: '该任务已经失效,请修改失效信息',
        duration: 7
      })
    } else {
      universalFetch(`${__SERVICE_API__}analysis/tasks/${data.id}/run`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'GET'
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          let mess2 = ''
          let mess1 = json.message.split(':')
          if (mess1.length > 1) {
            mess2 = mess1[1]
          } else {
            mess2 = json.message
          }
          notification.error({
            message: '任务启动提醒',
            description: mess2,
            duration: 7
          })
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.props.refreshTaskList(data)
        notification.open({
          message: '任务启动提醒',
          description: '任务启动成功'
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
    }
  }

  render () {
    const { data } = this.props
    const { modelPresent } = this.state
    const component = this
    let switchvalue = ''
    if (modelPresent) {
      const isUseful = data.model.useFul
      switchvalue = <a title={this.state.disableLable}><Switch checkedChildren={'可用'} unCheckedChildren={'不可用'}
        onChange={this.closeModel} defaultChecked={isUseful} disabled={this.state.disabled} /></a>
    }
    return (
      <div className={styles['actions']}>
        <Popconfirm title='确定要运行此任务吗'
          arrowPointAtCenter
          placement='left'
          onConfirm={this.runTask}
          >
          <Tooltip placement='topLeft' title='运行'>
            <Button
              size='small'
              icon='caret-right'
              style={{ marginRight: '10px' }}
            />
          </Tooltip>
        </Popconfirm>
        <Tooltip placement='topLeft' title='编辑'>
          <Button
            size='small'
            style={{ marginRight: '10px' }}
            icon='edit'
            onClick={() => {
              component.getTaskData()
            }}
          />
        </Tooltip>
        <Popconfirm title='确定要删除此任务吗'
          arrowPointAtCenter
          placement='left'
          onConfirm={this.deleteTask}
          >
          <Button
            size='small'
            icon='delete'
            type='danger'
            style={{ marginRight: '10px', color: '#F04134' }}
            ghost
          />
        </Popconfirm>
        &nbsp;
        {
          switchvalue
        }
      </div>
    )
  }
}

export default TaskListActions
